from flask import Flask,render_template,request,jsonify,escape
from panduan import panduan_login
from geo import weatherInfo
import pandas as pd
Mai_key = "217fc9b3f26daa32adb8c391fe0a372f"

app = Flask(__name__)

def log_request(req:"flask_request",res:str):
	with open("view.log","a") as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep="|")

@app.route("/")
def hello() -> str:
	return "hello world"

@app.route("/entry")
def entry_page() -> 'html':
	return render_template('entry.html',the_title ="欢迎进入实时天气查询系统")

@app.route("/search",methods = ['POST'])
def search() -> 'html':
	phrase = request.form["phrase"]
	letters = request.form["letters"]
	a = panduan_login(phrase,letters)
	print(a)
	# environs = request.environs
	user_input = request.form['City']
	geoone = weatherInfo(Mai_key,user_input)
	# geotwo = pd.json_normalize(geoone['geocodes'][0])

	if a =="true":
		province1 = geoone["lives"][0]['province']
		city1 = geoone["lives"][0]['city']
		adcode1 = geoone["lives"][0]['adcode']
		weather1 = geoone["lives"][0]['weather']
		temperature1 = geoone["lives"][0]['temperature']
		winddirection1 = geoone["lives"][0]['winddirection']
		windpower1 = geoone["lives"][0]['windpower']
		humidity1 = geoone["lives"][0]['humidity']
		reporttime1 = geoone["lives"][0]['reporttime']
		result1 = str(province1)+str(city1)+str(adcode1)+str(weather1)+str(temperature1)+str(windpower1)+str(humidity1)+str(reporttime1)
		log_request(request,result1)
		return render_template('results.html',
			the_title = "登入成功，欢迎进入主页",
			the_geocode = geoone,
			province = province1,
			city = city1,
			adcode = adcode1,
			weather = weather1,
			temperature = temperature1,
			winddirection = winddirection1,
			windpower = windpower1,
			humidity = humidity1,
			reporttime = reporttime1
			)
	else:
		return "账号或密码错误，登入查询失败"


@app.route("/results",methods =["GET"])
def results_page() -> "html":
	return render_template('results.html',the_title ="welcome to searchletters on the web")

@app.route("/viewlog")
def hello_viewlog():
	with open("view.log","r") as log:
		contents = []
		for item in log:
			contents.append([])
			for i in item.split("|"):
				contents[-1].append(escape(i))
	# return str(contents)
		
	log_title = ["Form data","Remote_addr","User_agent","results"]
	return render_template("view.html",title1 = "查看日志",the_data = contents,the_log_title = log_title)

if __name__ =='__main__':
	app.run(debug = True)